package com.iphanta.community.activity.photographic.common;

import com.iphanta.community.common.utils.RedisKeyUtils;
import lombok.Data;
import lombok.Getter;
import lombok.ToString;
import org.redisson.api.RBucket;
import org.redisson.api.RTransaction;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 墨声 E-mail: zehong.hongframe.huang@gmail.com
 * create time: 4/12/22 10:09 AM
 */
@Data
@ToString
public class BallBox implements java.io.Serializable {

    private String activityId;

    private Long entryId;

    private Long dynamicId;

    /**
     * 每轮曝光次数 * 轮数
     */
    private Integer total;

    /**
     *  被曝光总次数
     */
    private Integer exposure;

    /**
     * 红球
     */
    private Integer red;

    public BallBox() {
        this.exposure = 0;
    }

    public BallBox(Long dynamicId, Integer total) {
        this.dynamicId = dynamicId;
        this.total = total;
        this.red = total;
        this.exposure = 0;
    }

    public BallBox(Long dynamicId, Integer total, Integer red) {
        this.dynamicId = dynamicId;
        this.total = total;
        this.red = red;
        this.exposure = 0;
    }

    public void exposure(RTransaction transaction) {
        try {
            String boxKey = RedisKeyUtils.INSTANCE.key("bucket_ball_box", String.valueOf(this.dynamicId));
            RBucket<BallBox> bucket =  transaction.getBucket(boxKey);
            BallBox box = bucket.get();
            this.red = --box.red;
            this.exposure = ++box.exposure;
            bucket.set(box);
            transaction.commit();
        } catch (Exception e) {
            transaction.rollback();
        }
    }
}
